<template>
  <div id="userLoginPage">
    <h2 class="title">用户登录</h2>
    <a-form
        style="max-width: 480px; margin: 0 auto"
        label-align="left"
        :model="formState"
        name="basic"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          label="名字"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
      >
        <a-input v-model:value="formState.username" placeholder="请输入用户名"/>
      </a-form-item>

      <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }, {min:8, message: '密码不能小于8位'}]"
      >
        <a-input-password v-model:value="formState.password" placeholder="请输入密码"/>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 3, span: 21 }">
        <a-button type="primary" html-type="submit" @click="onHandleSubmit(formState)">登录</a-button>
      </a-form-item>
    </a-form>
  </div>

</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import {userLogin} from "@/api/user";
import {useLoginStore} from "@/store/useLoginUserStore";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";

const loginStore = useLoginStore();
const router = useRouter();

interface FormState {
  username: string;
  password: string;
}

const formState = reactive<FormState>({
  username: '',
  password: '',
});

/**
 * 提交表单——登录
 */
const onHandleSubmit = async (values: any) => {
  const res = await userLogin(values);
  if(res.data.code === 200 && res.data.data){
    // 登录成功
    await loginStore.fetchLoginUser();
    message.success("登录成功");
    router.push({
      path: '/',
      replace: true  // 点击返回不会回到上一页面
    })
  }else{
    message.error("注册失败," + res.data.msg);
  }
};

const onFinish = (info: any) => {

}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
</script>

<style scoped>
#userLoginPage .title{
  margin-bottom: 16px;
  text-align: center;
}
</style>


